package org.smart4j.charpter2.util;

import org.apache.commons.lang3.StringUtils;

/**
 * 转型操作工具类
 * @author 蒋贵强
 *
 */
public final class CastUtil {
	
	/**
	 * 转为String型，默认为空串
	 * @param obj
	 * @return
	 */
	public static String castString(Object obj){
		return castString(obj,"");
	}

	/**
	 * 转为String类型，提供默认值
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static String castString(Object obj,String defaultValue){
		return null == obj ? defaultValue:String.valueOf(obj);
	}
	
	/**
	 * 转换为double类型，默认为0
	 * @param obj
	 * @return
	 */
	public static double castDouble(Object obj){
		return castDouble(obj,0);
	}
	
	/**
	 * 转为double类型，需要提供默认值
	 * @param obj
	 * @param defaultDouble
	 * @return
	 */
	public static double castDouble(Object obj,double defaultDouble){
		double doubleValue = defaultDouble;
		if(obj != null){
			String strValue = castString(obj);
			if(StringUtils.isNotEmpty(strValue)){
				try {
					doubleValue = Double.parseDouble(strValue);
				} catch (Exception e) {
					doubleValue = defaultDouble;
				}
			}
		}
		return doubleValue;
	}
	
	/**
	 * 转换为LONG型，默认为0
	 * @param obj
	 * @return
	 */
	public static long castLong(Object obj){
		return castLong(obj,0);
	}
	
	/**
	 * 转换为long型，提供默认值
	 * @param obj
	 * @param defaultLong
	 * @return
	 */
	public static long castLong(Object obj,long defaultLong){
		long longValue = defaultLong;
		if(obj != null){
			String strValue = castString(obj);
			if(StringUtils.isNotEmpty(strValue)){
				try {
					longValue = Long.parseLong(strValue);
				} catch (Exception e) {
					longValue = defaultLong;
				}
			}
		}
		return longValue;
	}
	
	/**
	 * 转换为int型，默认为0
	 * @param obj
	 * @return
	 */
	public static int castInt(Object obj){
		return castInt(obj,0);
	}
	
	/**
	 * 转换为int型提供默认值
	 * @param obj
	 * @param defaultInt
	 * @return
	 */
	public static int castInt(Object obj,int defaultInt){
		int intValue = defaultInt;
		if(obj != null){
			String strValue = castString(obj);
			if(StringUtils.isNotEmpty(strValue)){
				try {
					intValue = Integer.parseInt(strValue);
				} catch (Exception e) {
					intValue = defaultInt;
				}
			}
		}
		return intValue;
	}
	
	/**
	 * 转换为boolean型，默认false
	 * @param obj
	 * @return
	 */
	public static boolean castBoolean(Object obj){
		return castBoolean(obj,false);
	}
	
	/**
	 * 转换为boolean型 提供默认值
	 * @param obj
	 * @param defaultBoolean
	 * @return
	 */
	public static boolean castBoolean(Object obj,boolean defaultBoolean){
		boolean booleanValue = defaultBoolean;
		if(obj != null){
			String strValue = castString(obj);
			booleanValue = Boolean.parseBoolean(strValue);
		}
		return booleanValue;
	}
}
